package sun.flower.leetcode;

/**
 * 求和：求和指定数组的指定下标之间的和，包括两个下标
 * @Author :tuhan
 * @Date : 2021/3/1 21:55
 **/
public class NumArraySumRange {

/*
    private  int[] numArray ;

    public NumArraySumRange(int[] numArray) {
        this.numArray = numArray;
    }

    public  int sumRange(int i, int j) {
        int sum = 0;

        if(i<=j && i>=0){
            if(j<numArray.length){
                for(int x = i;x<=j;x++){
                    sum+=numArray[x];
                }
            }
        }

        return sum;
    }
*/

    int[] sums;

    public NumArraySumRange(int[] nums) {
        int n = nums.length;
        sums = new int[n + 1];
        for (int i = 0; i < n; i++) {
            sums[i + 1] = sums[i] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
}

    public static void main(String[] args){
        int[] numArray = {0,-9,3,7,6,10};
        NumArraySumRange numArraySumRange = new NumArraySumRange(numArray);
        int sum = numArraySumRange.sumRange(2,4);
        System.out.println(sum);
    }
}
